package com.m3958.firstgwt.server.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import nl.captcha.Captcha;

import com.google.gson.JsonArray;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import com.m3958.firstgwt.server.model.XinJian;
import com.m3958.firstgwt.server.model.XinJianCat;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.ReqParaService;


@Singleton
public class XinJiansServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static String ERROR_TPL = "{\"meta\":{\"startRow\":null,\"rowNum\":null,\"totalNum\":null},\"success\":false,\"data\":null,\"errors\":[{\"codes\":null,\"arguments\":null,\"defaultMessage\":\"%s\",\"objectName\":\"com.m3958.newxyzcms.domain.Xinjian\",\"field\":\"%s\",\"rejectedValue\":null,\"bindingFailure\":false,\"code\":null}]}";


	
	@Inject
	private Injector injector;
	
	@Inject
	private AppUtilService autils;
	
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;
	
	
	/*
	 * 1、不需要任何输出
	 * 2、输出document.write
	 * 3、输出callback
	 */
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) 
	                               throws ServletException, IOException {
		
	}
	
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) 
	                               throws ServletException, IOException {
		createXj(req, res);
	}
	
//	{"meta":{"startRow":null,"rowNum":null,"totalNum":null},"success":false,"data":null,
//	"errors":[{"codes":null,"arguments":null,"defaultMessage":"m3958-duplicateField","objectName":"com.m3958.newxyzcms.domain.Xinjian","field":"authorityName","rejectedValue":null,"bindingFailure":false,"code":null}]}
	
	
//	{"meta":{"startRow":0,"rowNum":1,"totalNum":1},"success":true,"data":[{"authorityName":"ssddd","createdAt":1342523101913,"id":151,"version":1}],"errors":null}
	
	@Transactional
	public void createXj(HttpServletRequest req, HttpServletResponse res) throws IOException {
		ReqParaService reqps = injector.getInstance(ReqParaService.class);
		
		String captchaAnswer = req.getParameter("captcha_answer");
		
		Captcha captcha = (Captcha) req.getSession().getAttribute(Captcha.NAME);
		
		if (captcha == null || !captcha.isCorrect(captchaAnswer)){
			String resstr = String.format(ERROR_TPL,"验证码不匹配","captcha_answer");
			sendRes(req, res,resstr);
			return;
		}
		
		int siteid = reqps.getIdValue("siteid");
		if(siteid == -1){
			sendRes(req, res, "必须设定siteid");
			return;
		}
		
		int xjcatid = reqps.getIdValue("xjcatid");
		
		if(xjcatid == -1){
			sendRes(req, res, "必须设定xjcatid");
			return;
		}
		
		XinJian xj = new XinJian();
		xj.setAudit(false);
		xj.setBaomima(reqps.getStringValue("baomima"));
		xj.setContent(reqps.getStringValue("content"));
		xj.setCreatedAt(new Date());
		xj.setDanwei(reqps.getStringValue("danwei"));
		xj.setDianhua(reqps.getStringValue("dianhua"));
		xj.setDizhi(reqps.getStringValue("dizhi"));
		xj.setEmail(reqps.getStringValue("email"));
		xj.setGongkai(reqps.getBooleanValue("gongkai"));
		xj.setLeixing(reqps.getStringValue("leixing"));
//		xj.setPublishedAt();
//		xj.setReply("");
//		xj.setRepliedAt(null);
//		xj.setShengri(null);
		xj.setShouji(reqps.getStringValue("shouji"));
		xj.setSiteId(siteid);
		xj.setState("UNTOUCHED");
		xj.setTitle(reqps.getStringValue("title"));
//		xj.setTplName(null);
		xj.setXingbie(reqps.getStringValue("xingbie"));
		xj.setXingming(reqps.getStringValue("xingming"));
		xj.setYoubian(reqps.getStringValue("youbian"));
		
		emp.get().persist(xj);
		
		XinJianCat xjc = emp.get().find(XinJianCat.class, xjcatid);
		
		xjc.getXinjians().add(xj);
		emp.get().merge(xjc);
		
		JSONObject jo = new JSONObject();
		jo.element("meta", new JSONObject().element("startRow", 0).element("rowNum", 1).element("totalNum", 1));
		jo.element("success", true);
		
		JSONArray dataField = new JSONArray();
		dataField.add(xj.toJson());
		jo.element("data", dataField);
		sendRes(req, res, jo.toString());
	}
	
	private void sendRes(HttpServletRequest req, HttpServletResponse res,String resstr) throws IOException{
		
		res.setContentType("application/json; charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		Writer w = res.getWriter();
		w.write(resstr);
		w.flush();
		w.close();
	}

	
}
